package org.protester.core;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

import org.protester.base.EntityBase;

@Entity
public class Comment extends EntityBase {

	@Column(nullable = false)
	private String comment;

	@OneToOne(cascade = CascadeType.PERSIST)
	private Comment parent;

	@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "parent")
	private Set<Comment> children = new HashSet<Comment>();

	@ManyToOne(cascade = CascadeType.PERSIST)
	@JoinColumn()
	private CommentContainer container;

	public Comment() {
	}

	public Comment(String comment) {
		this.comment = comment;
	}

	public String getComment() {
		return comment;
	}

	public void setComment(String comment) {
		this.comment = comment;
	}

	public Comment getParent() {
		return parent;
	}

	public void setParent(Comment parent) throws CommentException {

		if (parent.equals(this))
			throw new CommentException(
					"O comentario nao pode ser seu proprio pai.");

		if (!parent.getChildren().contains(this))
			parent.addChild(this);
		else
			this.parent = parent;
	}

	public Set<Comment> getChildren() {
		return children;
	}

	public void addChild(Comment child) throws CommentException {

		if (child.equals(this))
			throw new CommentException(
					"O comentario nao pode ser seu proprio filho.");

		if (child.getParent() != null)
			throw new CommentException("O comentario ja possui um pai");

		children.add(child);
		child.setParent(this);
	}

	public void setChildren(Set<Comment> children) {
		this.children = children;
	}

	public CommentContainer getContainer() {
		return container;
	}

	public void setContainer(CommentContainer container)
			throws CommentException {

		if (!container.getComments().contains(this))
			container.addComment(this);
		else
			this.container = container;
	}

}